import React from 'react'
import { Tabs } from 'antd-mobile'
import { connect } from 'react-redux'
import { Toast } from 'antd-mobile'
import {
  Video,
  Abort,
  Comment,
  CommentList,
  TopicContent,
  CommentPop,
  PopUp,
  Catalog,
  CatalogItem
} from './style'

import {
  courseDetails,
  addComment,
  comments,
  catalogues,
  oldLearn,
  saveRecord,
  workList
} from '../../api'

class Index extends React.PureComponent {
  constructor(prop) {
    super(prop)
    this.state = {
      isShow: false,
      isPopShow: false,
      workInfo: '',
      catalogIndex: 0,
      coursesInfo: '',
      commentContent: '',
      menu: [],
      isPlay: false,
      currUnit: '',
      oldCourses: ''
    }
  }
  componentDidMount() {
    this.getDetail()
    this.getMen()
    this.getOldCourse()
    this.getComments()

    // 监听视频
    let that = this
    let md = document.getElementById('video')
    md &&
      md.addEventListener('ended', function() {
        that.setState({
          isPlay: false,
          isPopShow: true
        })
        // that.showPopXx()
      })
    md &&
      md.addEventListener('paused', function() {
        that.setState({
          isPlay: false
        })
      })
  }
  componentWillUnmount() {
    saveRecord({
      subject_id: this.state.coursesInfo.subject_id,
      course_id: this.props.match.params.id,
      member_id: this.props.userInfo.id,
      course_time: this.state.coursesInfo.video_duration,
      learned_time: this.formatSeconds(
        document.getElementById('video') &&
          document.getElementById('video').currentTime
      )
    }).then(res => {
      console.log('保存学习进度')
    })
  }
  // 换算成小时;
  formatSeconds(value) {
    var theTime = parseInt(value) // 秒
    var theTime1 = 0 // 分
    var theTime2 = 0 // 小时

    if (theTime > 60) {
      theTime1 = parseInt(theTime / 60)
      theTime = parseInt(theTime % 60)

      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60)
        theTime1 = parseInt(theTime1 % 60)
      }
    }

    var result = parseInt(theTime)
    return parseInt(theTime2) + ':' + parseInt(theTime1) + ':' + result
  }
  // 换算成秒
  formatToSecond(value) {
    let arr = (value + '').split(':')
    if (arr.length === 3) {
      return parseInt(arr[0] * 60 * 60) + parseInt(arr[1] * 60 + arr[2])
    }
    if (arr.length === 1) {
      return arr[0]
    }
    if (arr.length === 0) {
      return 0
    }
    return arr[0] * 60 + arr[1]
  }
  getComments() {
    comments({
      cid: this.props.match.params.id
    }).then(res => {
      this.setState({
        commentList: res.data.data
      })
    })
  }
  getOldCourse() {
    oldLearn({
      mid: this.props.userInfo.id,
      cid: this.props.match.params.id
    }).then(res => {
      if (res.data.code === 0) {
        this.setState({
          oldCourses: res.data.data
        })
        // 设置上次播放进度
        if (
          document.getElementById('video') &&
          this.state.coursesInfo.video_uri
        ) {
          document.getElementById('video').currentTime = this.formatToSecond(
            res.data.data.learned_time
          )
        }
      }
    })
  }
  getDetail() {
    courseDetails({
      id: this.props.match.params.id
    }).then(res => {
      this.setState({
        coursesInfo: res.data.data
      })
      // 获取作业
      workList({
        cid: this.props.match.params.id,
        sid: res.data.data.subject_id
      }).then(res => {
        this.setState({
          workInfo: res.data.data
        })
      })
    })
  }
  getMen() {
    catalogues({
      sid: this.props.match.params.id
    }).then(res => {
      this.setState({
        menu: res.data.data
      })
    })
  }
  changeComment(obj) {
    this.setState({
      commentContent: obj.target.value
    })
  }
  // 提交评论
  sendComment() {
    if (!this.state.commentContent) {
      Toast.info('请输入内容', 3)
      return false
    }
    addComment({
      course_id: this.props.match.params.id,
      member_id: this.props.userInfo.id,
      content: this.state.commentContent
    }).then(res => {
      this.hidePop()
      this.getDetail()
      this.getComments()
      Toast.info(res.data.message, 3)
    })
  }
  showPop() {
    this.setState({
      isShow: true
    })
  }
  showPopXx() {
    this.setState({
      isPopShow: true
    })
  }
  hidePopXx() {
    this.setState({
      isPopShow: false
    })
  }
  hidePop(e) {
    if (e && !e.target.id) {
      return false
    }
    this.setState({
      isShow: false
    })
  }
  showCatalog(i) {
    this.setState({
      catalogIndex: i
    })
  }
  goTopic() {
    this.props.history.push(
      '/topic/' +
        this.state.workInfo.subject_id +
        '/' +
        this.props.match.params.id
    )
  }
  getCourse(id) {
    window.location.href = `/course/${id}`
    // this.props.history.push('/course/'+id)
  }
  play() {
    document.getElementById('video').play()
    this.setState({
      isPlay: true
    })
  }

  render() {
    let tabs = [
      { title: '简介', sub: '0' },
      { title: '目录', sub: '1' },
      {
        title: `评论(${
          this.state.coursesInfo ? this.state.coursesInfo.evaluates : 0
        })`,
        sub: '2'
      },
      { title: '答题', sub: '3' }
    ]
    return (
      <div
        style={{
          minHeight: '100vh',
          background: '#fff',
          display: 'flex',
          flexDirection: 'column'
        }}
      >
        {this.state.coursesInfo && (
          <Video>
            {!this.state.isShow && (
              <video
                id="video"
                controls
                src={this.state.coursesInfo.video_uri}
              />
            )}
            {!this.state.isPlay && (
              <div className="bg" onClick={this.play.bind(this)}>
                <i className="iconfont">&#xe601;</i>
                <h3>
                  最近学到：
                  {this.state.coursesInfo.title}
                </h3>
                <button>继续学习</button>
                <div className="time">
                  上次学习至
                  {this.state.oldCourses
                    ? this.state.oldCourses.learned_time
                    : '00:00:00'}
                </div>
              </div>
            )}
          </Video>
        )}

        <Tabs
          tabs={tabs}
          initialPage={0}
          tabBarActiveTextColor="#c29c5d"
          tabBarUnderlineStyle={{ borderColor: '#c29c5d' }}
          onChange={(tab, index) => {
            console.log('onChange', index, tab)
          }}
          onTabClick={(tab, index) => {
            console.log('onTabClick', index, tab)
          }}
        >
          <Abort>
            {this.state.coursesInfo && this.state.coursesInfo.describe}
            <Comment onClick={this.showPop.bind(this)}>
              <i className="iconfont write">&#xe61c;</i>
              <input type="text" readOnly placeholder="写下对课程的评论吧" />
              <i className="iconfont">&#xe710;</i>
            </Comment>
          </Abort>

          <Catalog>
            {this.state.menu &&
              this.state.menu.map((item, index) => {
                return (
                  <CatalogItem key={item.id}>
                    <div
                      className="title"
                      onClick={this.showCatalog.bind(this, 0)}
                    >
                      <span>{index < 9 ? '0' + (index + 1) : index + 1}</span>
                      {item.title}
                      <i
                        className={
                          this.state.catalogIndex !== 0 ? 'iconfont' : 'none'
                        }
                      >
                        &#xe7f2;
                      </i>
                      <i
                        className={
                          this.state.catalogIndex === 0 ? 'iconfont' : 'none'
                        }
                      >
                        &#xe63b;
                      </i>
                    </div>
                    <ul className={this.state.catalogIndex === 0 ? 'show' : ''}>
                      {item.units &&
                        item.units.map((chilren, index) => {
                          return (
                            <CatalogItem
                              onClick={this.getCourse.bind(this, chilren.id)}
                              key={chilren.id}
                              className={
                                parseInt(chilren.id) ===
                                parseInt(this.props.match.params.id)
                                  ? 'sub atthis'
                                  : 'sub'
                              }
                            >
                              <span>课程{index + 1}</span>
                              {chilren.title}
                            </CatalogItem>
                          )
                        })}
                    </ul>
                  </CatalogItem>
                )
              })}
          </Catalog>

          <CommentList>
            {this.state.commentList &&
              this.state.commentList.map(item => {
                return (
                  <li key={item.id}>
                    <img src={item.member.avatar} alt={item.member.nickname} />
                    <div className="hidden">
                      <h3>
                        {item.member.nickname}
                        <span>{item.created_at.split(' ')[0]}</span>
                      </h3>
                      <div>{item.content}</div>
                    </div>
                  </li>
                )
              })}
          </CommentList>
          <TopicContent>
            {this.state.workInfo && (
              <div>
                <p>{this.state.workInfo.describe}</p>
                <button onClick={this.goTopic.bind(this)}>去做作业</button>
              </div>
            )}
          </TopicContent>
        </Tabs>

        <CommentPop
          id="popUp"
          className={this.state.isShow ? 'show' : ''}
          onClick={this.hidePop.bind(this)}
        >
          <div className="cont">
            <p>写评论</p>
            <i className="iconfont write">&#xe61c;</i>
            <textarea
              name=""
              id=""
              cols="30"
              onChange={this.changeComment.bind(this)}
              rows="10"
              placeholder="写点什么吧！"
            />
            <b onClick={this.sendComment.bind(this)}>发表</b>
          </div>
        </CommentPop>

        <Comment onClick={this.showPop.bind(this)}>
          <i className="iconfont write">&#xe61c;</i>
          <input type="text" readOnly placeholder="写下对课程的评论吧" />
          <i className="iconfont">&#xe710;</i>
        </Comment>

        <PopUp className={this.state.isPopShow ? 'show' : ''}>
          <div className="content">
            <h2>学习奖励说明</h2>
            <p>
              完整观看一个专业视频，可获0.5元心意奖；答对一道专业题目，可获0.5元心意奖；（提现可联系客服）学习完视频并且答对每道专业题，可获得职业“推荐人”特权,赚取每瓶产品的差价以及发展团队。
            </p>
            <b onClick={this.hidePopXx.bind(this)}>确定</b>
            <i className="iconfont" onClick={this.hidePopXx.bind(this)}>
              &#xe628;
            </i>
          </div>
        </PopUp>
      </div>
    )
  }
}
const mapStateToProps = state => ({
  userInfo: state.userInfo
})

export default connect(mapStateToProps)(Index)
